package com.nmcc.app_adherence;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OtherTasks extends Activity {
	SQLiteDatabase db;
	SQLiteDatabase dbMain;
	
	Spinner spnCompletedAdherenceHouses;
	Spinner spnNotCompletedAdherenceHouses;
	
	Spinner spnHousesExported;
	
	Spinner spnHousesToBeExported;
	Spinner spnHousesFinalised;

	 private File root;
	 private ArrayList<File> fileList = new ArrayList<File>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_other_tasks);

		//File dbfile = new File(dir+"/0000000000000001.db"); 
		//dbMain = SQLiteDatabase.openOrCreateDatabase("/data/data/com.nmcc.app_adherence/databases/mis_data", null);
		//db.close();
		
		String dir = Environment.getExternalStorageDirectory().getPath();
		File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
		
		if (dbfile.exists()){
			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
		}
				
		//System.out.println("Its open? "  + db.isOpen());
		
		addItemsOnListViewCompleteAdherenceHouses();
		addItemsOnListViewNotCompleteAdherenceHouses();
		
		//addItemsOnListViewMonitoringExportedHouses();
		//addItemsOnListViewMonitoringToBeExportedHouses();
		
		
		
		//addItemsOnListViewFinalizedMonitoringHouses();
		//db.close(); 
		//dbMain.close();
		
		//Button btnmarkunfollwedup=(Button)findViewById(R.id.btnMakeUnDueForFollowUp);
		//btnmarkunfollwedup.requestFocus();
	  
        Button b666 = (Button) findViewById(R.id.btnMakeUnDueForFollowUp);
        b666.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {

        	  //ReconcileODKAndCSVCompletedHouses(arg0);
        	   int markAsDueAs1NotDueAs2=2;
        	   MakeHousesOfCertainDateDueForFollowUpd(arg0, markAsDueAs1NotDueAs2 );//markAsDueAs1NotDueAs2
           }
        });  
        
  	  
        Button b99 = (Button) findViewById(R.id.btnMakeDueForFollowUp);
        b99.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {

        	   MakeAllHousesNotFollowedUp(arg0);
        	   
        	  //ReconcileODKAndCSVCompletedHouses(arg0);
        	   int markAsDueAs1NotDueAs2=1;
        	   MakeHousesOfCertainDateDueForFollowUpd(arg0, markAsDueAs1NotDueAs2 );//markAsDueAs1NotDueAs2
           }
        });  
        
        Button b90 = (Button) findViewById(R.id.btnExtractDataFromPhone);
        b90.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {

        	   ExportGPSPersonsDataToCSVExtractFromPhone(arg0);
           }
        });  
        

        
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.other_tasks, menu);
		return true;
	}

	 // add items into spinner dynamically
	public void addItemsOnListViewCompleteAdherenceHouses() {
    	spnCompletedAdherenceHouses = (Spinner) findViewById(R.id.spnHousesCompletedByTestingPair);
    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
      List list = new ArrayList();
      //add all the house get name personid
      //for loop
      int numrecs=0;
		    Cursor cursor = db.rawQuery("SELECT * FROM household2 where _savepoint_type='COMPLETE'", null);
		    if (cursor.moveToFirst())
		    {
		        do
		        {
		        	 list.add(cursor.getString(15) + " - " + cursor.getString(11));
		        	 numrecs=numrecs+1;
		        	 
		        } while(cursor.moveToNext());
		    }

		   // db.close();  
	        	ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
	    	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    	     // spnHouseEditspn.setAdapter(dataAdapter);
	    	     spnCompletedAdherenceHouses.setAdapter(dataAdapter);
	    	     
	    	     //lblHousesCompletedByTestingPair
	    	     TextView mylabel = (TextView) findViewById(R.id.lblHousesCompletedByTestingPair);
	    	     String originaltext=mylabel.getText().toString();;
	    	     
	    	     mylabel.setText(originaltext + " (" + numrecs + ")");
    }	    

	public void addItemsOnListViewNotCompleteAdherenceHouses() {
		spnNotCompletedAdherenceHouses = (Spinner) findViewById(R.id.spnHousesNotCompletedByTestingPair);
    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
      List list = new ArrayList();
      //add all the house get name personid
      //for loop
      int numrecs=0;
		    Cursor cursor = db.rawQuery("SELECT * FROM household2 where _savepoint_type is null", null);
		    if (cursor.moveToFirst())
		    {
		        do
		        {
		        	 list.add(cursor.getString(15) + " - " + cursor.getString(11));
		        	 numrecs=numrecs+1;
		        	 
		        } while(cursor.moveToNext());
		    }

		    //db.close();  
	        	ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
	    	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    	     // spnHouseEditspn.setAdapter(dataAdapter);
	    	     spnNotCompletedAdherenceHouses.setAdapter(dataAdapter);
	    	     
	    	     //lblHousesCompletedByTestingPair
	    	     TextView mylabel = (TextView) findViewById(R.id.lblHousesNotCompletedByTestingPair);
	    	     String originaltext=mylabel.getText().toString();;
	    	     
	    	     mylabel.setText(originaltext + " (" + numrecs + ")");
    }	    

	   public void ReadFromExternalDatabases(View view){
	  	   MySQLiteHelperOtherDatabases db = new MySQLiteHelperOtherDatabases(this);
	  	   //to avoid overwriting in odk survey just send to sd card folder
	         // add Books
	         //db.DropAllTables();
	       db.GetHouseNameAndIDForListing("06872212-45a7-44d9-a090-7c80184db2f0");

	  }
	   
	   
	   public void addItemsOnListViewMonitoringExportedHouses(){
			MySQLiteHelper mh = new MySQLiteHelper(this);
		   	MySQLiteHelper db1 = new MySQLiteHelper(this);
		   	
			SQLiteDatabase db33 = mh.getReadableDatabase();
			
			//String hs_id = db1.GetSetting(3);

			spnHousesExported = (Spinner) findViewById(R.id.spnExportedHouseholds);
	      List list = new ArrayList();
	      	
	      int numrecs=0;
			
	    //}
	 	
	 		//now add the data, same order as above, check corresponding fields

	 
	    	Cursor rs = db33.rawQuery("SELECT * FROM GPSData where WasExported=1", null);
		         //String[] args = {"tagname", "tagname", "tagname", "tagname", "tagname"};
		         //Cursor rs = db33.query(table, columns, null, null, null, null, null);		

	      if(rs.moveToFirst()){
	           do{

		        		list.add(rs.getString(14) + " - " + rs.getString(8));
		        		 numrecs=numrecs+1;
		        		 
	             }while(rs.moveToNext());
	         }
			      ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
		 	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 	     // spnHouseEditspn.setAdapter(dataAdapter);
		 	    spnHousesExported.setAdapter(dataAdapter);
	 	 
		 	   TextView mylabel = (TextView) findViewById(R.id.lblExportedHouseholds);
	    	     String originaltext=mylabel.getText().toString();
	    	     
	    	     mylabel.setText(originaltext + " (" + numrecs + ")");
		 	    
	       rs.close();
	       db33.close();
	 }	    

	   public void addItemsOnListViewMonitoringToBeExportedHouses(){
				MySQLiteHelper mh = new MySQLiteHelper(this);
			   	MySQLiteHelper db1 = new MySQLiteHelper(this);
			   	
				SQLiteDatabase db33 = mh.getReadableDatabase();
				
				//String hs_id = db1.GetSetting(3);

				spnHousesToBeExported = (Spinner) findViewById(R.id.spnHousesToBeExported);
		      List list = new ArrayList();
		      	
		      int numrecs=0;
				
		    //}
		 	
		 		//now add the data, same order as above, check corresponding fields

		 
		    	Cursor rs = db33.rawQuery("SELECT * FROM GPSData where WasExported=0", null);
			         //String[] args = {"tagname", "tagname", "tagname", "tagname", "tagname"};
			         //Cursor rs = db33.query(table, columns, null, null, null, null, null);		

		      if(rs.moveToFirst()){
		           do{

			        		list.add(rs.getString(14) + " - " + rs.getString(8));
			        		 numrecs=numrecs+1;
			        		 
		             }while(rs.moveToNext());
		         }
				      ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
			 	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			 	     // spnHouseEditspn.setAdapter(dataAdapter);
			 	    spnHousesToBeExported.setAdapter(dataAdapter);
		 	 
			 	   TextView mylabel = (TextView) findViewById(R.id.lblHousesToBeExported);
		    	     String originaltext=mylabel.getText().toString();
		    	     
		    	     mylabel.setText(originaltext + " (" + numrecs + ")");
			 	    
		       rs.close();
		       db33.close();
		 }	    

	   public void addItemsOnListViewFinalizedMonitoringHouses() {
		   spnHousesFinalised = (Spinner) findViewById(R.id.spnFinalizedHouseholds);
	    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
	      List list = new ArrayList();
	      //add all the house get name personid
	      //for loop
	      int numrecs=0;
			    Cursor cursor = db.rawQuery("SELECT * FROM household", null);
			    if (cursor.moveToFirst())
			    {
			        do
			        {
			        	 list.add(cursor.getString(15) + " - " + cursor.getString(11));
			        	 numrecs=numrecs+1;
			        	 
			        } while(cursor.moveToNext());
			    }

			    //db.close();  
		        	ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
		    	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	     // spnHouseEditspn.setAdapter(dataAdapter);
		    	     spnHousesFinalised.setAdapter(dataAdapter);
		    	     
		    	     //lblHousesCompletedByTestingPair
		    	     TextView mylabel = (TextView) findViewById(R.id.lblFinalizedHouseholds);
		    	     String originaltext=mylabel.getText().toString();;
		    	     
		    	     mylabel.setText(originaltext + " (" + numrecs + ")");
	    }	    
			
  
	   public void MakeHousesOfCertainDateDueForFollowUpd(View view, int markAsDueAs1NotDueAs2) {
		   SQLiteDatabase db;
			
		   String dir = Environment.getExternalStorageDirectory().getPath();
			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
		   
			Toast.makeText(getApplicationContext(), "This is only for houses which have not yet been completed.", 5000).show();

			  // spnNotCompletedAdherenceHouses = (Spinner) findViewById(R.id.spnHousesNotCompletedByTestingPair);
	    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
	      List list = new ArrayList();
	      //add all the house get name personid
	      //for loop
	      
	      String houseid;

	      
	      DatePicker mydatePicker = (DatePicker) findViewById(R.id.date_picker);
	     // String selectedDate = DateFormat.getDateInstance().format(mydatePicker.getCalendarView().getDate());
	      int year=mydatePicker.getYear();
	      int month=mydatePicker.getMonth();
	      int day=mydatePicker.getDayOfMonth();//calender seems month needs adding plus 1

	      String date1= "'" + year + "-" + String.format("%02d",  month + 1)  + "-" + String.format("%02d",  day) + "%'"; //ignore time after percentage get just date
    
		  //2014-10-06T11:18:21.942000000
	  	//Toast.makeText(getApplicationContext(), date1, Toast.LENGTH_LONG).show();


	      
	      int numrecs=0;							//all houses done on that date
			    Cursor cursor = db.rawQuery("SELECT * FROM gpsdata where DateTaken LIKE " + date1, null);
			    if (cursor.moveToFirst())
			    {
			        do
			        {
			        	 
			        	
			        	
			        	
			        	//list.add(cursor.getString(14) + " - " + cursor.getString(11));

			        	     houseid = cursor.getString(11);
			        	     boolean housewascompleted=false;
			        	     					//check if house was completed
			        		    Cursor cursor2 = db.rawQuery("SELECT * FROM household2 where household_id='" + houseid + "' and hvist_result='_1'", null);
			    			    if (cursor2.moveToFirst())
			    			    {
			    			        do
			    			        {
			    			        	 //list.add(cursor.getString(14) + " - " + cursor.getString(11));
			    			        	housewascompleted=true;
			    			        	//Toast.makeText(getApplicationContext(), "house found completed", Toast.LENGTH_LONG).show();

			    			        		
			    			         } while(cursor2.moveToNext());
			    			    }
			    			    
			    			    
			        	          if (!housewascompleted){
			        	        	  //Toast.makeText(getApplicationContext(), "house not found completed", Toast.LENGTH_LONG).show();

						        	    if (markAsDueAs1NotDueAs2==1){
						        	    	
							        	      db.execSQL("UPDATE gpsdata SET " +
							        		      		"DueForFollowUp=1 WHERE household_id='" + houseid + "'");
							        	      		
					        	         }	 
						        	     else if (markAsDueAs1NotDueAs2==2){
						        	    	 db.execSQL("UPDATE gpsdata SET " +
							        		      		"DueForFollowUp=0 WHERE household_id='" + houseid + "'");
       	     
						        	     }
			        	          }
		        	    
			        } while(cursor.moveToNext());
			    }

			    db.close();  
		    	     
			    Toast.makeText(getApplicationContext(), "Completed marking houses.", 5000).show();


		  //creategpsdataTableInODK();
		   
		  //ExportGPSDataTakeToODKDirectNewMethod(view, 1, "no comment", "placename", "newhouseguid" );
		  // List list = new ArrayList();
		      //add all the house get name personid
		      //for loop
		   //String household_id_got="kkkkk";
		   
		      //int numrecs=0;
				 //   Cursor cursor = db.rawQuery("SELECT * FROM household2 where hvisit_result='_1'", null);
				   // if (cursor.moveToFirst())
				   // {
				       // do
				       // {
				        	 //list.add(cursor.getString(17) + " - " + cursor.getString(11));
				        	// numrecs=numrecs+1;
				        	 //get householdid
				        	// household_id_got=cursor.getString(17);
				        	 
				        	// ContentValues cv = new ContentValues();
	  			        	//  cv.put("HHResult", "_1");
				        	// String dataToInsert
				        	// String where = "id='?'";
				        	 //String[] whereArgs= new String[] {household_id_got};
				        	 
				        	// db.update("gpsdata",  cv, where,  whereArgs);
				        	 
				     	   //Toast.makeText(getApplicationContext(), "nnnnnnnn", 5000).show();
				     	   
				        	 
				        //} while(cursor.moveToNext());
				        
				      
				        
				   // }
				    	//db.close();

	      
		   
	   }	
		 
	   
	   public void MakeAllHousesNotFollowedUp(View view) {
		   SQLiteDatabase db;
			
		   String dir = Environment.getExternalStorageDirectory().getPath();
			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
		   String houseid;
		   
			//Toast.makeText(getApplicationContext(), "This is only for houses which have not yet been completed.", 5000).show();

			  // spnNotCompletedAdherenceHouses = (Spinner) findViewById(R.id.spnHousesNotCompletedByTestingPair);
	    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
	      List list = new ArrayList();
	      //add all the house get name personid
	      //for loop
	      
	  //2014-10-06T11:18:21.942000000
	  	//Toast.makeText(getApplicationContext(), date1, Toast.LENGTH_LONG).show();
  
	      int numrecs=0;							//all houses done on that date
			    Cursor cursor = db.rawQuery("SELECT * FROM gpsdata", null);
			    if (cursor.moveToFirst())
			    {
			        do
			        {
			        	//Toast.makeText(getApplicationContext(), cursor.getString(11), 5000).show();

			        						houseid=cursor.getString(11);//get house_id field

						        	    	 db.execSQL("UPDATE gpsdata SET " +
							        		      		"DueForFollowUp=0 WHERE household_id='" + houseid + "'");
		        	    
			        } while(cursor.moveToNext());
			    }

			    db.close();  
		    	     
			    //Toast.makeText(getApplicationContext(), "Completed marking houses.", 5000).show();


		  //creategpsdataTableInODK();
		   
		  //ExportGPSDataTakeToODKDirectNewMethod(view, 1, "no comment", "placename", "newhouseguid" );
		  // List list = new ArrayList();
		      //add all the house get name personid
		      //for loop
		   //String household_id_got="kkkkk";
		   
		      //int numrecs=0;
				 //   Cursor cursor = db.rawQuery("SELECT * FROM household2 where hvisit_result='_1'", null);
				   // if (cursor.moveToFirst())
				   // {
				       // do
				       // {
				        	 //list.add(cursor.getString(17) + " - " + cursor.getString(11));
				        	// numrecs=numrecs+1;
				        	 //get householdid
				        	// household_id_got=cursor.getString(17);
				        	 
				        	// ContentValues cv = new ContentValues();
	  			        	//  cv.put("HHResult", "_1");
				        	// String dataToInsert
				        	// String where = "id='?'";
				        	 //String[] whereArgs= new String[] {household_id_got};
				        	 
				        	// db.update("gpsdata",  cv, where,  whereArgs);
				        	 
				     	   //Toast.makeText(getApplicationContext(), "nnnnnnnn", 5000).show();
				     	   
				        	 
				        //} while(cursor.moveToNext());
				        
				      
				        
				   // }
				    	//db.close();

	      
		   
	   }	
		 
	   
		 public void ExportGPSDataTakeToODKDirectNewMethod(View view, int newAs1ExistingAs2, String comment, String placename, String newhouseguid ){
  			 SQLiteDatabase db;
  			 
  			String dir = Environment.getExternalStorageDirectory().getPath();
  			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
  			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
  			
  				//UUID uuid = UUID.randomUUID();
  				//String newhouseguid=uuid.toString();
  				if (newAs1ExistingAs2==2){
  			        	 // db.execSQL("UPDATE GPSData SET " +
  			      		//"HouseNumber=" + HouseNumber + 
  			      		//"', comment='" + comment + "' WHERE HouseID='" + HouseID + "'");
  		               }
  			          else if (newAs1ExistingAs2==1){
  	                      //2014-10-06-10.57.45.666000000
  			        	  //2014-10-05T22:53:34.293000000
  			        	  
  			        	  //2014-10-06T11:08:19.894000000
  			        	  //2014-10-06T11:18:21.942000000
  			        	Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  			         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.");
  			          //yyyy-MM-dd'T'HH:mm:ssZ
  			          
  			          format.setTimeZone(TimeZone.getDefault()); // Set the TimeZone to whatever you are expecting.
  			         String timestampedDate = format.format(timestamp) + String.format("%09d", timestamp.getNanos());

  		
  			       newhouseguid="d04cec94-c8e2-4f9d-9a44-f943ace82ef1";
  			         
  			        	  ContentValues cv = new ContentValues();
  			        	  cv.put("_id", "uuid:"+ newhouseguid);
  			        	cv.put("_sync_state", "new_row"); 
  			        	 cv.put("_form_id", "gpsdata_new"); 
  			        	 cv.put("_locale", "default"); 
  			        	cv.put("_savepoint_timestamp", timestampedDate); //redo time need .89000000000
  			        	cv.put("_savepoint_creator", "anonymous"); 
//d04cec94-c8e2-4f9d-9a44-f943ace82ef1	55	2	9/3/2014 20:42	9/3/2014	mhrr	
//_10		HOUSEHOLD PRESENT	g	28.32525826	-15.4508548	0	
//d04cec94-c8e2-4f9d-9a44-f943ace82ef1
  			        	 
  			        	  //housedetails
  			        	cv.put("HouseID", "d04cec94-c8e2-4f9d-9a44-f943ace82ef1"); 
  			        	cv.put("HouseNumber", "55"); 
  			        	cv.put("ClusterNumber", "2"); 
  			        	cv.put("DateTaken", "9/3/2014 20:42"); 
  			        	cv.put("PlaceName", "mungailaaaaaaaaa"); 
  			        	cv.put("HHResult", "_10"); 
  			        	cv.put("HHResultOther", "HOUSEHOLD PRESENT"); 
  			        	cv.put("HHResultLabel", "g"); 
  			        	cv.put("Longitude", "28.32525826");
  			        	cv.put("Latitude", "-15.4508548");
  			        	cv.put("HDOP", "0");
  			        	cv.put("household_id", "d04cec94-c8e2-4f9d-9a44-f943ace82ef1");
  			        	cv.put("comment", "be level comment");
  			        	
  			        	  db.insert("gpsdata", null, cv);
  			        	  //db.close();
  			          }

  				
  			          db.close(); 
  		
  		}   

  
		 public void ExportGPSPersonsDataToCSVExtractFromPhone(View view){
				
			   
				
		  	   MySQLiteHelper db = new MySQLiteHelper(this);
		  	   //to avoid overwriting in odk survey just send to sd card folder
		         // add Books
		  	   String filenameGPS, filenamePersons, filenameODKDatabase,filenameMalaria;
		  	 filenameGPS="GPSData Extracted " + getPhoneMDAName() + ".csv";
		  	filenamePersons="Persons Extracted " + getPhoneMDAName() + ".csv";
		  	filenameODKDatabase="ODK Survey Extracted " + getPhoneMDAName() + ".csv";
		  	filenameMalaria="Malaria Profile Extracted " + getPhoneMDAName() + ".csv";
		  	
		  	Toast.makeText(getApplicationContext(), "Files will be extracted to sdcard. Files are named: " + filenameGPS + " and " + filenamePersons, Toast.LENGTH_LONG).show();
		           
		  	   
		  	   //db.DropAllTables();
		       db.ExportGPSDataToCSVExtractFromPhone(filenameGPS);
		        //db.getGPSRecordsCount();
		    
		       db.ExportPersonsToCSVExtractFromPhone(filenamePersons);

		      // db.ExportMalariaProfileToCSVExtractFromPhone(filenameMalaria);
		       
		       SendFileViaBluetoothFromSDCardFolder(view,filenameGPS,filenamePersons,filenameMalaria);
		       
		  }
			public String getPhoneMDAName(){
				String phon="nophonename";
				//File root = Environment.getExternalStorageDirectory();
				File root=new File(Environment.getExternalStorageDirectory() + "/opendatakit/username");
				
				getfile(root);
				
				if (root.exists()){
					 //Toast.makeText(getApplicationContext(), fileList.get(0).getName(), 5000).show();
						
					//for (int i=0; i< fileList.size(); i++){
						phon= fileList.get(0).getName();
						return phon;
					//}
				}
					
				
				return phon;
				
			}
				
				public ArrayList getfile(File dir) { 
					File listFile[] = dir.listFiles(); 
					if (listFile != null && listFile.length > 0) { 
						for (int i = 0; i < listFile.length; i++) { 
							if (listFile[i].isDirectory()) { 
								fileList.add(listFile[i]); 
								getfile(listFile[i]); 
								} else { 
									//if (listFile[i].getName().endsWith(".txt")) 
									//{ 
										fileList.add(listFile[i]);
									//} 
								} 
						}
					} return fileList;
				}
				
				
				 public void SendFileViaBluetoothFromSDCardFolder(View view, String filenameGPSData, String filenamePersons, String malariaprofile){
		
					   File sdcard = Environment.getExternalStorageDirectory();
						   File f1=new File(sdcard+"/" + filenameGPSData);
						   File f2=new File(sdcard+"/" + filenamePersons);
						   //also odk main database
						   File f3= new File(sdcard+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db");
						   //malariaprofile
						   //File f4=new File(sdcard+"/" + malariaprofile);
						   
						   Uri csvUri1 = Uri.fromFile(f1);
						   Uri csvUri2 = Uri.fromFile(f2);
						   Uri csvUri3 = Uri.fromFile(f3);
						  // Uri csvUri4 = Uri.fromFile(f4);
						   
						   ArrayList<Uri> csvUris = new ArrayList<Uri>();
						   csvUris.add(csvUri1); // Add your image URIs here
						   csvUris.add(csvUri2);	
						   csvUris.add(csvUri3);
						   //csvUris.add(csvUri4);
						   
					 //...
					   // inside method
					   // Check if bluetooth is supported
					   BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
					   if (btAdapter == null) {
					   // Device does not support Bluetooth
					   // Inform user that we're done.     
					   }
					   // bring up Android chooser
					   Intent intent = new Intent();
					   intent.setAction(Intent.ACTION_SEND_MULTIPLE);
					   
					   //intent.setType("application/csv");
					   //send file 1
					   //intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );
					   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, csvUris);
					   
					   //remove below to have flexibilty on the bluetooth complete action
					   //intent.setPackage("com.mediatek.bluetooth");//"com.android.bluetooth"
					   //can remove above line, or make it as a setting editable
					   
					   //...
					   //startActivity(intent);
					   //send file 2

					   intent.setType("application/csv");
					   startActivity(Intent.createChooser(intent, "Send GPSData and Persons Files Via:"));
					  //startActivity(intent);
					

					    
					} 



				
}
